(function() {
  'use strict';

  angular
    .module('zadminWeb')
    .controller('InterfaceController', InterfaceController);

  /** @ngInject */
  function InterfaceController($scope, $http, $resource) {

    $scope.params="";
    $scope.interfaceList=[];
    $scope.restMethod = {};

    $http.get("./config/conf.json").success(function(data) {
      $scope.config = data;

      $scope.interfaceList = $scope.config.interfaceList;

      $scope.interface = {interfaceName:$scope.config.defaultUrl,params:"userName=test&password=e10adc3949ba59abbe56e057f20f883e"};

      $scope.interfaceType = "3";

      $scope.returnStr = "返回值";
    });

    $scope.selectIndex = 0;
    /* $scope.selectChange = function(index) {
     $scope.interfaceName = $scope.interfaceList[$scope.selectIndex].interfaceName;
     $scope.params = $scope.interfaceList[$scope.selectIndex].params;
     } */

    $scope.$watch("interfaceName",function() {
      var length = $scope.interfaceList.length;
      for(var i = 0;i<length;i++) {
        if($scope.interfaceList[i].interfaceName == $scope.interfaceName) {
          $scope.params = $scope.interfaceList[i].params;
          return;
        }
      }
    });

    $scope.submit = function() {

      var obj = {};
      //判断最后一位是否为逗号
      if($scope.params.length>0) {
        var sub=$scope.params.substr($scope.params.length-1,1);
        if(sub=="&"){
          //移除字符串最后一位逗号
          $scope.params=$scope.params.substring(0,$scope.params.length-1);
        }
        //因使用逗号分隔
        obj = $scope.match($scope.params);
      }

      if($scope.interfaceType == "1") {
        $http.post($scope.interfaceName,
          $.param(obj),
          {headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}})
          .success(function(data) {
            $scope.returnStr = data;
          }).error(function(data) {
            console.log(data);
          });
      } else if($scope.interfaceType == "2") {
        $http.post($scope.config.baseUrl + $scope.interfaceName,obj,{
            headers:{'userid':'1'}
          }
        ).success(function(data) {
          $scope.returnStr = data;
        }).error(function(data) {
          $scope.returnStr = data;
        });
      } else {
        var restParam = $scope.match($scope.restMethod.params);

        $http.defaults.headers.common['test'] = Math.random();
        var src = $resource($scope.config.baseUrl + $scope.interface.interfaceName,restParam);
        var result = src[$scope.restMethod.methodName]();
        $scope.returnStr = result;
        //src.delete({itemId:1},{},function(data) {
        //    console.log("error");
        //},
        //function(error) {
        //  console.log("error");
        //});
      }
    };

    $scope.match = function(str) {
      if(str.indexOf("=")<0) {
        return str;
      }
      var obj = {};
      var paramlist = str.split('&');

      for(var x=0;x<paramlist.length;x++) {
        var strValue = paramlist[x];
        var index = strValue.indexOf("=");
        if(index<0) {
          console.log("格式不正确，未找到“＝”");
        }
        var key = strValue.substring(0,index);
        var value = strValue.substring(index+1,strValue.length);
        if(value.substring(0,1)=="[") {
          if(value.substring(value.length-1,value.length)=="]") {
            var content = value.substring(1,value.length-1);
            var list = content.split(',');
            var array = [];
            for(var i = 0;i<list.length;i++) {
              array[i] = $scope.match(list[i]);
            }
            obj[key] = array;
          } else {
            console.log("格式不正确，[]没有对称闭合");
          }
        } else {
          if(isNaN(parseInt(value))) {
            obj[key]=value;
          } else {
            obj[key] = parseInt(value);
          }
        }
      }


      return obj;

    };

    $scope.toPrettyJSON = function (objStr) {
      try {
        //var obj = $parse(objStr)({});
        var result = JSON.stringify(objStr, null, Number(4));
        return result;
      }catch(e){
        // eat $parse error
        return objStr;
      }
    };
  }
})();
